package org.sfgeeq.framework.helper;

import org.sfgeeq.framework.annotation.Action;
import org.sfgeeq.framework.bean.Handler;
import org.sfgeeq.framework.bean.Request;
import org.sfgeeq.framework.util.ArrayUtil;
import org.sfgeeq.framework.util.CollectionUtil;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * controller 控制器助手类
 * Created by on 2016/8/26.
 */
public final class ControllerHelper {
    /**
     * 用于存放请求与处理的映射关系(简称Action Map)
     */
    private static final Map<Request,Handler> ACTION_MAP=new HashMap<Request, Handler>();
//静态块
    static {
        //获取所有Controller类
    Set<Class<?>> controllerClassSet=ClassHelper.getControllerClassSet();
    if(CollectionUtil.isNotEmpty(controllerClassSet)){
        //遍历controller类中定义的方法
        for(Class<?> controllerClass:controllerClassSet){
            //获取controller类中定义的方法
            Method[] methods=controllerClass.getDeclaredMethods();
            if(ArrayUtil.isNotEmpty(methods)){
                for(Method method:methods){
                    //判断当前方法是否带有Action注解
                    if(method.isAnnotationPresent(Action.class)){
                        //从action注解中获取URL映射规则
                        Action action=method.getAnnotation(Action.class);
                        String mapping=action.value();
                        //验证URL映射规则 用正值表达式验证
                        if(mapping.matches("\\w+:/\\w*")){
                            String [] array =mapping.split(":");
                            if(ArrayUtil.isNotEmpty(array)&&array.length==2){
                                //获取请求方法与请求路径
                                String requestMethod=array[0];
                                String requestPath=array[1];

                                Request request=new Request(requestMethod,requestPath);
                                Handler handler=new Handler(controllerClass,method);

                                //初始化ACTION MAP
                                ACTION_MAP.put(request,handler);
                            }
                        }
                    }
                }
            }
        }
    }
    }

    public static Handler getHandler(String requestMethod,String requestPath){
        Request request=new Request(requestMethod,requestPath);
        return ACTION_MAP.get(request);
    }
}
